<?php
include_once( 'mysql.php' );
include_once( 'saetv2.ex.class.php' );

$con = mysql_connect(MYSQL_HOST . ':' . MYSQL_PORT, MYSQL_USER, MYSQL_PASS);

if (!$con) {
	die('Could not connect: ' . mysql_error());
}

mysql_select_db(MYSQL_DB, $con);

$sql = 'select st.id source_target_id, s.user_id source_user_id, 
	t.id target_id, t.user_id target_user_id, t.access_token target_access_token 
	from bif_source_target st, bif_source s, bif_target t
	where st.source_id = s.id and st.target_id = t.id and st.enabled = 1';

$result = mysql_query($sql);

$action = $_REQUEST['action'];

$tOAuthV2 = new SaeTOAuthV2(NULL, NULL);
$tClientV2 = new SaeTClientV2($tOAuthV2);

while ($row = mysql_fetch_array($result)) {
	$sourceTargetId = $row['source_target_id'];
	$sourceUserId = $row['source_user_id'];
	$targetId = $row['target_id'];
	$targetUserId = $row['target_user_id'];
	$targetAccessToken = $row['target_access_token'];
	
	if ($targetAccessToken != '') {
		$tOAuthV2->access_token = $targetAccessToken;
		
		if (validateAccessToken($tOAuthV2, $targetAccessToken)) {
			if ('add' == $action) {
				if (!isTableSourceTargetFollowersNotAddedExisted($sourceUserId, $targetUserId)) {
					createTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId);
					addUserIdsToTableSourceTargetFollowersNotAdded($tClientV2, $sourceUserId, $targetUserId);
				}

				if (!isTableSourceTargetFollowersAddedExisted($sourceUserId, $targetUserId)) {
					createTableSourceTargetFollowersAdded($sourceUserId, $targetUserId);
				}
				
				if (!isTableSourceTargetLogsExisted($sourceUserId, $targetUserId)) {
					createTableSourceTargetLogs($sourceUserId, $targetUserId);
				}
				
				$userIds = fetchUserIdsFromTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId);
				
				$successfulUserIdsCount = 0;
				$failedUserIdsCount = 0;
				
				for ($i = 0; $i < count($userIds); $i++) {
					$userId = $userIds[$i];
					
					deleteUserIdsFromTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId, $userId);
					
					$createdUserId = createFollow($tClientV2, $userId);
					
					if ($createdUserId != '') {
						$successfulUserIdsCount++;
						
						addUserIdsToTableSourceTargetFollowersAdded($sourceUserId, $targetUserId, $createdUserId);
					} else {
						$failedUserIdsCount++;
					}
				}
				
				logResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount);
				showResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount);
			} else if ('delete' == $action) {
				$userIds = fetchUserIdsFromTableSourceTargetFollowersAdded($sourceUserId, $targetUserId);
				
				$successfulUserIdsCount = 0;
				$failedUserIdsCount = 0;
				
				for ($i = 0; $i < count($userIds); $i++) {
					$userId = $userIds[$i];
					
					deleteUserIdsFromTableSourceTargetFollowersAdded($sourceUserId, $targetUserId, $userId);
					
					$destroyedUserId = destroyFollow($tClientV2, $userId);
					
					if ($destroyedUserId != '') {
						$successfulUserIdsCount++;
					} else {
						$failedUserIdsCount++;
					}
				}
				
				if (!isTableSourceTargetFollowersAddedNotEmpty($sourceUserId, $targetUserId)) {
					deleteTableSourceTargetLogs($sourceUserId, $targetUserId);
					
					deleteTableSourceTargetFollowersAdded($sourceUserId, $targetUserId);
					
					deleteTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId);
					
					setSourceTargetDisabled($sourceTargetId);
				}
				
				logResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount);
				showResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount);
			}
		} else {
			clearTargetAccessToken($targetId);
		}
	}
}

mysql_close($con);

//Start
function validateAccessToken($tOAuthV2, $accessToken) {
	try {
		$response = $tOAuthV2->getTokenInfo($accessToken);
		
		if ($response['expire_in'] > 0) {
			return TRUE;
		} else {
			return FALSE;
		}
	} catch (OAuthException $e) {
		return FALSE;
	}
}

function clearTargetAccessToken($targetId) {
	$sql = 'update bif_target set access_token = \'\' where id = ' . $targetId;
		
	mysql_query($sql);
}

//Add
function isTableSourceTargetFollowersNotAddedExisted($sourceUserId, $targetUserId) {
	$sql = 'show tables like \'bif_source_target_followers_notadded_' . $sourceUserId . '_' . $targetUserId . '\'';
	
	$result = mysql_query($sql);
	
	if (mysql_num_rows($result) != 0) {
		return TRUE;
	} else {
		return FALSE;
	}
}

function createTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId) {
	$sql = 'create table bif_source_target_followers_notadded_' . $sourceUserId . '_' . $targetUserId . ' (
  		id int not null auto_increment,
  		user_id varchar(20) not null,
  		created_datetime datetime not null,
  		primary key (id))';
	
	mysql_query($sql);
}

function fillTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId, $userIds) {
	$sql = 'insert into bif_source_target_followers_notadded_' . $sourceUserId . '_' . $targetUserId . ' (user_id, created_datetime) values ';
	
	for ($i = 0; $i < count($userIds); $i++) {
		$userId = $userIds[$i];
	
		if ($i + 1 < count($userIds)) {
			$sql = $sql . '(\'' . $userId . '\', now()),';
		} else {
			$sql = $sql . '(\'' . $userId . '\', now())';
		}
	}
	
	mysql_query($sql);
}

function addUserIdsToTableSourceTargetFollowersNotAdded($tClientV2, $sourceUserId, $targetUserId) {
	$cursor = 0;
	
	while (true) {
		$response = $tClientV2->followers_ids_by_id($sourceUserId, $cursor, 200);
		
		if (!isset($response['error']) && !isset($response['error_code'])) {
			$userIds = $response['ids'];
			fillTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId, $userIds);
			
			$cursor = $response['next_cursor'];
			
			if ($cursor == 0) {
				break;
			}
		} else {
			break;
		}
	}
}

function isTableSourceTargetFollowersAddedExisted($sourceUserId, $targetUserId) {
	$sql = 'show tables like \'bif_source_target_followers_added_' . $sourceUserId . '_' . $targetUserId . '\'';
	
	$result = mysql_query($sql);
	
	if (mysql_num_rows($result) != 0) {
		return TRUE;
	} else {
		return FALSE;
	}
}

function createTableSourceTargetFollowersAdded($sourceUserId, $targetUserId) {
	$sql = 'create table bif_source_target_followers_added_' . $sourceUserId . '_' . $targetUserId . ' (
		id int not null auto_increment,
		user_id varchar(20) not null,
		created_datetime datetime not null,
		primary key (id))';
	
	mysql_query($sql);
}

function isTableSourceTargetLogsExisted($source_user_id, $target_user_id) {
	$sql = 'show tables like \'bif_source_target_logs_' . $source_user_id . '_' . $target_user_id . '\'';

	$result = mysql_query($sql);
	
	if (mysql_num_rows($result) != 0) {
		return TRUE;
	} else {
		return FALSE;
	}
}

function createTableSourceTargetLogs($source_user_id, $target_user_id) {
	$sql = 'create table bif_source_target_logs_' . $source_user_id . '_' . $target_user_id . ' (
		id int not null auto_increment,
		message varchar(200) not null,
		created_datetime datetime not null,
		primary key (id))';

	mysql_query($sql);
}

function fetchUserIdsFromTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId) {
	$sql = 'select user_id from bif_source_target_followers_notadded_' . $sourceUserId . '_' . $targetUserId . ' limit 50';
	
	$result = mysql_query($sql);
	
	$userIds = array();
	
	while ($row = mysql_fetch_array($result)) {
		array_push($userIds, $row['user_id']);
	}
	
	return $userIds;
}

function createFollow($tClientV2, $userId) {
	$response = $tClientV2->follow_by_id($userId);
	
	if (!isset($response['error']) && !isset($response['error_code'])) {
		return $response['idstr'];
	} else {
		return '';
	}
}

function addUserIdsToTableSourceTargetFollowersAdded($sourceUserId, $targetUserId, $userId) {
	$sql = 'insert into bif_source_target_followers_added_' . $sourceUserId . '_'. $targetUserId . ' (user_id, created_datetime) 
		values (\'' . $userId . '\', now())';
	
	mysql_query($sql);
}

function deleteUserIdsFromTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId, $userId) {
	$sql = 'delete from bif_source_target_followers_notadded_' . $sourceUserId . '_' . $targetUserId . ' where user_id = ' . $userId;
	
	mysql_query($sql);
}

//Delete
function fetchUserIdsFromTableSourceTargetFollowersAdded($sourceUserId, $targetUserId) {
	$sql = 'select user_id from bif_source_target_followers_added_' . $sourceUserId . '_' . $targetUserId . ' where datediff(now(), created_datetime) > 2';

	$result = mysql_query($sql);

	$userIds = array();

	while ($row = mysql_fetch_array($result)) {
		array_push($userIds, $row['user_id']);
	}

	return $userIds;
}

function destroyFollow($tClientV2, $userId) {
	$response = $tClientV2->unfollow_by_id($userId);

	if (!isset($response['error']) && !isset($response['error_code'])) {
		return $response['idstr'];
	} else {
		return '';
	}
}

function deleteUserIdsFromTableSourceTargetFollowersAdded($sourceUserId, $targetUserId, $userId) {
	$sql = 'delete from bif_source_target_followers_added_' . $sourceUserId . '_' . $targetUserId . ' where user_id = ' . $userId;
	
	mysql_query($sql);
}

function isTableSourceTargetFollowersAddedNotEmpty($sourceUserId, $targetUserId) {
	$sql = 'select user_id from bif_source_target_followers_added_' . $sourceUserId . '_' . $targetUserId;

	$result = mysql_query($sql);

	if (mysql_num_rows($result) != 0) {
		return TRUE;
	} else {
		return FALSE;
	}
}

function deleteTableSourceTargetLogs($sourceUserId, $targetUserId) {
	$sql = 'drop table bif_source_target_logs_' . $sourceUserId . '_' . $targetUserId;

	mysql_query($sql);
}

function deleteTableSourceTargetFollowersAdded($sourceUserId, $targetUserId) {
	$sql = 'drop table bif_source_target_followers_added_' . $sourceUserId . '_' . $targetUserId;
	
	mysql_query($sql);
}

function deleteTableSourceTargetFollowersNotAdded($sourceUserId, $targetUserId) {
	$sql = 'drop table bif_source_target_followers_notadded_' . $sourceUserId . '_' . $targetUserId;
	
	mysql_query($sql);
}

function setSourceTargetDisabled($sourceTargetId) {
	$sql = 'update bif_source_target set enabled = 0 where id = ' . $sourceTargetId;
	
	mysql_query($sql);
}

//End
function getResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount) {
	$message = $sourceUserId . '_' . $targetUserId . ', ' . $action . ', successful ' . $successfulUserIdsCount . ', failed ' . $failedUserIdsCount . '.';
	
	return $message;
}

function showResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount) {
	echo getResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount);
}

function logResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount) {
	$message = getResultMessage($sourceUserId, $targetUserId, $action, $successfulUserIdsCount, $failedUserIdsCount);
	
	$sql = 'insert into bif_source_target_logs_' . $sourceUserId . '_'. $targetUserId . ' (message, created_datetime)
		values (\'' . $message . '\', now())';
	
	mysql_query($sql);
}
?>